What is the difference between Callable and Runnable in Java?
What is the difference between Callable and Runnable in Java?
1409
19-Jul-2024
Updated on 19-Jul-2024
Ashutosh Kumar Verma
19-Jul-2024Difference Between Callable and Runnable
Both Callable and Runnable are interfaces for describing tasks that can be executed simultaneously, usually by threads. Here is the main difference between Callable and Runnable.
Return Value
Runnable- The
run()
method of the Runnable interface does not return a result. A null method, means that it executes an event but returns no value.Callable- The
call()
method of the Callable interface returns a result of the specified type (specified by the generic type parameter<V>
). Thecall()
method can throw checked exceptions, which must be handled or thrown or declared.Handling Exception
Runnable- the
run()
method in Runnable cannot directly throw a noted exception. If it needs to throw a checked exception, it should be caught in therun(
) method and handled accordingly.Callable- the
call()
method in Callable can throw a flagged exception. These exceptions must be caught in thecall()
method or declared in thethrows
clause of the method.Usage with ExecutorService
Both the Runnable and the Callable can be passed to the ExecutorService for execution at the same time.
Example-
Runnable Syntax-
Example-
Callable Syntax-
Example-
Return Value Handling
Runnable- Since Runnable doesn’t return a value, you typically use a separate tool (such as a shared variable or some other synchronization technique) if you need to get a result or condition after a task is complete
Callable- When a Callable completes its execution, it returns a Future object that can be used to retrieve a statistic or to handle exceptions thrown during its execution.
Callable is an improvement over Runnable that lets functions return values and throw checked exceptions, providing greater flexibility in concurrent programming scenarios
Also, Read: How to achieve thread-safety in Java?